package homework.demo0604.mapper;



import homework.demo0604.pojo.UserInfo;

import homework.demo0604.util.DBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Component
public class UserMapper implements IUserMapper{
    @Autowired
    private DBUtil dbUtil;
    @Override
    public int insert(UserInfo userInfo) {
        try (Connection connection = dbUtil.getConnection();){
            String sql="INSERT INTO userinfo(username,password,nickname,age)" +
                    "VALUES (?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, userInfo.getUsername());
            ps.setString(2, userInfo.getPassword());
            ps.setString(3, userInfo.getNickname());
            ps.setInt(4,userInfo.getAge());
            int i = ps.executeUpdate();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public UserInfo select(String username) {
        UserInfo info = new UserInfo();
        try (Connection connection = dbUtil.getConnection();){

            String sql = "SELECT id,username,password,nickname,age FROM userinfo " +
                    "WHERE username = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()) {
                info.setId(rs.getInt("id"));
                info.setUsername(rs.getString("username"));
                info.setPassword(rs.getString("password"));
                info.setNickname(rs.getString("nickname"));
                info.setAge(rs.getInt("age"));
                return info;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
